package com.singleton.qaDemo;

import com.singleton.HungrySingleton;

import java.io.*;

// 序列化 破坏单例模式
public class SerializationBreaks {

    // 桌面a.txt文件
    private static String path = "C:\\Users\\Sans\\Desktop\\a.txt";

    public static void main(String[] args) throws Exception{

        // HungrySingleton类 需要序列化
        HungrySingleton hungrySingleton = HungrySingleton.getInstance();
        // 序列化存储
        writeObjectFile(hungrySingleton);
        // 反序列化提取
        HungrySingleton hungrySingleton1 = readObjectFromFile();

        // 根据地址进行判断他们是否相同
        System.out.println("hungrySingleton = " + hungrySingleton);
        System.out.println("hungrySingleton1 = " + hungrySingleton1);
    }

    // 从文件中读取对象
    public static HungrySingleton readObjectFromFile() throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
        HungrySingleton instance = (HungrySingleton) ois.readObject();
        return instance;
    }

    // 写入对象文件
    public static void writeObjectFile(HungrySingleton instance) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
        //将instance对象写出到文件中
        oos.writeObject(instance);
    }
}
